<script>
/*
 * @Author: Your name
 * @Date:   2020-06-23 22:43:02
 * @Last Modified by:   Your name
 * @Last Modified time: 2020-07-21 23:15:31
 */
</script>
<template>
  <div id="home">
    <!-- 顶部导航 -->
    <nav-bar>
      <div slot="left"></div>
      <div slot="center"><span>购物街</span></div>
      <div slot="right"></div>
    </nav-bar>
    <!-- 这里也放置一个tabcontrol组件的原因：基于better-scroll组件本身的使用transform的原因，在对滑动区域中的组件
    设置了position：fixed以后没法得到预期的效果的 而是会出现消失的问题，因此我们在scroll滑动区域的外面也放一个tabcontrol -->
    <tab-control
        :titles="['流行', '新款', '精选']"
        class="tab-control"
        @typeClick="typeClick"
        ref="tabControl1"
        :class="{TCisShow:tabControlIsShow}"
        v-show="tabControlIsShow"
      ></tab-control>
    <scroll
     class="content"
     ref="scroll" 
     :probe-type="3" 
     @scroll="scrollPosition"
     :pull-up-load="true"
     @pullingUp="loadMore"
     ><!-- 注意驼峰值得问题 -->
      <!-- 轮播图 -->
      <child-component @swiperIsLoad = "tabOffsetTop"></child-component>
      <!-- 推荐部分 -->
      <recommend></recommend>
      <!-- 本周流行 -->
      <liuxing></liuxing>
      <!-- 导航切换部分 -->
      <tab-control
        :titles="['流行', '新款', '精选']"
        class="tab-control"
        @typeClick="typeClick"
        ref="tabControl2"
      ></tab-control>
      <goods-list :goods="goods[currentType].list"></goods-list>
      
      
    </scroll>
    <!-- 返回按钮 --> 
    <back-top @click.native="clickBackTop" v-show = "isShowBackTop"></back-top>
  </div>
</template>
<script>
import NavBar from "../../components/common/navbar/NavBar.vue";
import ChildComponent from "./childComp/HomeSwiper.vue";
import Recommend from "../../components/content/comment/Comments.vue";
import Liuxing from "./childComp/LiuXing.vue";
import TabControl from "../../components/content/tabControl/TabControl.vue";
import GoodsList from "../../components/content/goods/GoodsList.vue";
import Scroll from "../../components/common/scoll/Scroll.vue";
import BackTop from "../../components/common/backtop/BackTop.vue";

import { getHomeMainData } from "../../network/home.js";
import { debounce } from "../../common/utils.js";
export default {
  data() {
    return {
      pageindex: 0,
      goods: {
        pop: { page: 0, list: [] },
        new: { page: 0, list: [] },
        sell: { page: 0, list: [] }
      },
      currentType:'pop',
      isShowBackTop:false,
      tabControlOffsetTop:0,
      tabControlIsFixed:false,
      tabControlIsShow:false,
      saveY:0,
      itemImgListener: null
    };
  },
  components: {
    NavBar,
    ChildComponent,
    Recommend,
    Liuxing,
    TabControl,
    GoodsList,
    Scroll,
    BackTop
  },
  created() {
    this.getGoodsList("pop");
    this.getGoodsList("new");
    this.getGoodsList("sell");
    
    //在这created里面监听的是有可能获取不到this.$refs.scroll的，把他最好写在mounted里面
    // this.$bus.$on('itemImageLoad',() => {
    //   // console.log('图片加载了');
    //   this.$refs.scroll.scrollRefresh();
    // });
  },
  mounted(){
    //接收防抖函数返回的函数(这个函数中的第二个参数可以省略，因为时间间隔即使是0，setTimeout函数也会延迟执行)
    const refresh = debounce(this.$refs.scroll.scrollRefresh);
    //为data中声明的图片相关的参数进行赋值
    this.itemImgListener = () => {
       console.log('图片加载了');
      //这样会导致刷新次数太频繁，影响性能，考虑利用防抖函数解决
      // this.$refs.scroll.scrollRefresh();
      refresh();
    }
    this.$bus.$on('itemImageLoad', this.itemImgListener);
  },
  methods: {
    //根据curerntType的值请求数据
    getGoodsList(type) {
      let page = this.goods[type].page + 1;
      getHomeMainData(type, page).then(res => {
        // console.log(type, res.message);
        this.goods[type].list.push(...res.message);
        this.goods[type].page += 1;

        //完成下拉加载更多(因为默认只会监听一次上拉加载更多，必须要告诉上拉加载完成了才能做到每次划到底部加载更多)
        this.$refs.scroll.scrollFinish();
      });
      // this.$refs.scroll.scroll.refresh();
    },
    //点击tab-control部分切换currentType值
    typeClick(index){
        // console.log(index)
        
        switch (index) {
            case 0:
                this.currentType = 'pop';
                break;
            case 1:
                this.currentType = 'new';
                break;
            case 2:
                this.currentType = 'sell';
                break;
            default:
                break;
        }
        // 让两个tabcontrol点击的数据同步
        this.$refs.tabControl1.currentIndex = index;
        this.$refs.tabControl2.currentIndex = index;
    },
    // //防抖函数  这种工具类的函数一般要抽离出来，写在commen文件夹中的utils.js文件中
    // debounce(func, delay){
    //   let timer = null;
    //   return function(...args){
    //     if(timer){
    //       clearTimeout(timer);
    //     }
    //     timer = setTimeout(() => {
    //       func.apply(this, args)
    //     }, delay);
    //   }
    // },
    //点击置顶按钮自动回到页面的顶部
    clickBackTop(){
      this.$refs.scroll.scrollTo(0, 0); //封装
    },
    //监听滚动的位置判断置顶的按钮是否显示，判断tabcontrol是否吸顶
    scrollPosition(position){
      // console.log(position);
      // console.log(this.isShowBackTop);
      this.isShowBackTop = (-position.y) > 1000;
      // console.log(this.tabControlIsFixed);
      this.tabControlIsFixed = (-position.y) > this.tabControlOffsetTop;
      this.tabControlIsShow = (-position.y) > this.tabControlOffsetTop;
    },
    //上拉加载更多商品数据函数
    loadMore(){
      // console.log('到底补了');
      this.getGoodsList(this.currentType);
    },
    //计算tabcontrol距离顶部的距离
    tabOffsetTop(){
      // console.log(this.$refs.tabControl2.$el.offsetTop);
      this.tabControlOffsetTop = this.$refs.tabControl2.$el.offsetTop;
    }
  },
  destroyed(){
    //通过给app.vue组件外面加上keep-alive阻止组件随便的销毁
    // console.log('home组件销毁了');
  },
  deactivated(){
    this.saveY = this.$refs.scroll.scrollY();
    // console.log('离开了');
    //离开时还要关闭事件总线中对goodslist组件的子组件goodsListItem中的itemImageLoad方法的监听。
    this.$bus.$off('itemImageLoad', this.itemImgListener);
  },
  activated(){
    this.$refs.scroll.scrollTo(0, this.saveY, 0);
    //最好进行一次刷新，避免出现页面回来以后页面异常的情况
    this.$refs.scroll.scrollRefresh();
    // console.log('进入了');
  }
//   computed:{
//       showGoods(){
//           return this.goods[this.currentType].list;
//       }
//   }
};
</script>
<style lang="css" scoped>
#home {
  /* padding-top: 44px; */
  /* padding-bottom: 49px; */
  position: relative;
  height: 100vh;  /* 占视口大小的百分之百 */
}
.content{
  /* 滑动区域大小的控制：
    1. 先设置父元素最大的那个高度为100vh，设置成相对定位（子绝父相）
    2. 采用绝对定位的方式，中间的位置大小自动撑开，设置top，bottom的属性值分别是顶部和底部导航的大小
    3. 然后设置overflow：hidden属性
   */
  position: absolute;
  top: 44px;
  bottom: 49px;
  left: 0;
  right: 0;
  overflow: hidden;
}
.fixed{
  position: fixed;
  top: 44px;
  left: 0;
  right: 0;
}
.TCisShow{
  position: relative;
  z-index: 9;
}
</style>
